package cluster

import (
	"fmt"
	"time"

	"gitee.com/zfd81/dbrs/cluster/msgpb"
	proto "github.com/golang/protobuf/proto"
	"github.com/hashicorp/memberlist"
)

type Message struct {
	packet *msgpb.Packet
}

func (m *Message) Id() string {
	return fmt.Sprintf("%s:%d", m.Endpoint(), m.Timestamp())
}

func (m *Message) Action() msgpb.Action {
	return m.packet.Action
}

func (m *Message) Add(content string) {
	m.packet.Contents = append(m.packet.Contents, content)
}

func (m *Message) Get(index int) string {
	return m.packet.Contents[index]
}

func (m *Message) Timestamp() int64 {
	return m.packet.Timestamp
}

func (m *Message) User() string {
	return m.packet.User
}

func (m *Message) Endpoint() string {
	return m.packet.Endpoint
}

func (m *Message) Marshal() ([]byte, error) {
	m.packet.Timestamp = time.Now().Unix()
	m.packet.Endpoint = Self().ServAddress()
	return proto.Marshal(m.packet)
}

func (m *Message) Send() error {
	bytes, err := m.Marshal()
	if err != nil {
		return err
	}
	broadcasts.QueueBroadcast(&broadcast{
		msg:    bytes,
		notify: nil,
	})
	return nil
}

func UnmarshalMessage(bytes []byte) (*Message, error) {
	packet := &msgpb.Packet{}
	err := proto.Unmarshal(bytes, packet)
	if err != nil {
		return nil, err
	}
	return &Message{
		packet: packet,
	}, nil
}

func NewMessage(action msgpb.Action) *Message {
	return &Message{
		packet: &msgpb.Packet{
			Action: action,
		},
	}
}

type broadcast struct {
	msg    []byte
	notify chan<- struct{}
}

func (b *broadcast) Invalidates(other memberlist.Broadcast) bool {
	return false
}

func (b *broadcast) Message() []byte {
	return b.msg
}

func (b *broadcast) Finished() {
	if b.notify != nil {
		close(b.notify)
	}
}
